<?php

namespace app\admin\model\chase;


use think\Config;
use think\exception\HttpResponseException;
use think\Model;
use think\Request;
use think\Response;
use think\View as ViewTemplate;

class UserVipCoupon extends Model
{
    protected $autoWriteTimestamp = false;

    public static function createAndUpdate($user_vip_id, $coupons, $nums)
    {
        $data = [];
        foreach ($coupons as $val) {
            if ($nums[$val] <= 0) {
                return self::error('优惠券数量不能小于0');
            }
            $data[] = [
                'user_vip_id' => $user_vip_id,
                'coupon_id' => $val,
                'num' => $nums[$val]
            ];
        }
        return self::insertAll($data);
    }

    public static function error($message = '')
    {
        $type = Request::instance()->isAjax()
            ? Config::get('default_ajax_return')
            : Config::get('default_return_type');
        $result = [
            'code' => 0,
            'msg'  => $message,
            'data' => '',
            'url'  => null,
            'wait' => 3,
        ];
        if ('html' == strtolower($type)) {
            $template = Config::get('template');
            $view = Config::get('view_replace_str');

            $result = ViewTemplate::instance($template, $view)
                ->fetch(Config::get('dispatch_error_tmpl'), $result);
        }

        $response = Response::create($result, $type)->header([]);

        throw new HttpResponseException($response);
    }

    public static function del($user_vip_id)
    {
        return self::where('user_vip_id', $user_vip_id)->delete();
    }

    public static function getCoupons($user_vip_id)
    {
        return self::where('user_vip_id', $user_vip_id)->select();
    }
}
